<?php
class AjaxController extends Zend_Controller_Action
 {
    public function PreDispatch()
    {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
    }
    
    public function timetableAction() {
        $obj = new Pub_Model_Statistic();
        $start = $this->_getParam('start');
        $end = $this->_getParam('end');    
        //$start = '01-06-2012';
        //$end = '27-06-2012';
        $dayStart =  intval(substr($start, 0, 2));
        $dayEnd =  substr($end, 0, 2);
        $monthStart = intval(substr($start, 3, 2));
        $monthEnd = intval(substr($end, 3, 2));
        $yearStart =  substr($start, 6, 4);
        $yearEnd =  substr($end, 6, 4);
        
        //var_dump($obj->test());
        
        $currentDate = Zend_Date::now();
        $currentDay =  intval($currentDate->get(Zend_Date::DAY));
        $currentMonth =  intval($currentDate->get(Zend_Date::MONTH));
        
        $banner = 1; $context = 2; $blog = 3; $social = 4;
        $allProfit = $bannerProfit = $contextProfit = $blogProfit = $socialProfit = 0;        
        $date = 0;
        $dayStatistic = Array();
        //for ($monthStart = 0; $monthStart <= 12; $monthStart++) {
           // echo $monthStart;
        for ($dayStart; $dayStart <= $dayEnd; $dayStart++) {
            //выборка всех транзакций за текущей день                                                                      $yearEnd);               
            $dayTransactions = $obj->getDayPubTransactions($dayStart, $monthStart);
            foreach($dayTransactions as $val) {
                //подсчет суммы всех платежей за текущей день
                $allProfit = $val['sum(amount)'];
                $date = $val['date'];                
            }                        
            //выборка и подсчет всех транзакций баннеров
            $dayBannerTransactions =  $obj->getDaySelectTransactions($dayStart, $monthStart, $banner);            
            foreach ($dayBannerTransactions as $valBanner) {
                $bannerProfit = $valBanner['sum(amount)'];
            }
            //выборка и подсчет всех транзакций контекстной рекламы
            $dayContextTransactions = $obj->getDaySelectTransactions($dayStart, $monthStart, $context);
            foreach ($dayContextTransactions as $valContext) {
                $contextProfit = $valContext['sum(amount)'];
            }
            //выборка и подсчет всех транзакций микроблогов
            $dayBlogTransactions = $obj->getDaySelectTransactions($dayStart, $monthStart, $blog);
            foreach ($dayBlogTransactions as $valBlog) {
                $blogProfit = $valBlog['sum(amount)'];
            }
            //выборка и подсчет всех транзакций социальных сетей
            $daySocialTransactions = $obj->getDaySelectTransactions($dayStart, $monthStart, $social);
            foreach ($daySocialTransactions as $valSocial) {
                $socialProfit = $valSocial['sum(amount)'];
            }
            if ($date != null) {                
                $dayStatistic[$dayStart]['all_profit']     = round($allProfit, 2);
                $dayStatistic[$dayStart]['banner_profit']  = round($bannerProfit, 2);
                $dayStatistic[$dayStart]['context_profit'] = round($contextProfit, 2);
                $dayStatistic[$dayStart]['blog_profit']    = round($blogProfit, 2);
                $dayStatistic[$dayStart]['social_profit']  = round($socialProfit, 2);
                $dayStatistic[$dayStart]['date']           = date("d-m-Y",strtotime($date));                                              
            }
            $bannerProfit = $allProfit = $contextProfit = $blogProfit = $socialProfit = null;
            $date = null;             
        }
        //}
        $json = '{"statistic":['."\n";
        foreach ($dayStatistic as $arr) {
            $json.= "\n".'{'.'"all_profit": "'.$arr['all_profit'].'",';
            $json.= '"banner_profit": "'.$arr['banner_profit'].'",';
            $json.= '"context_profit": "'.$arr['context_profit'].'",';
            $json.= '"blog_profit": "'.$arr['blog_profit'].'",';
            $json.= '"social_profit": "'.$arr['social_profit'].'",';
            $json.= '"date": "'.$arr['date'].'"';
            $json.= '},';                                                
        }            
        echo '], ', "\n", "\n" ,'"status": "OK"', "\n", '}';
        $json = substr($json, 0,-1);
        $this->_response->appendBody($json);      
    }   
    
    public function jsonAction() {
        $code = $this->_getParam('code');
        $adver = new Application_Model_Adver();
        $selectSpace = $adver->getSelectAdvSpace($code);
        $idSpace = $selectSpace['id'];
        $contextAdvers = $adver->getSpaceContextAdvers($idSpace);                      
        $json = '{"test":['."\n";
        foreach ($contextAdvers as $key => $context) {            
            $id = $context['id'];            
            $href = 'http://contextca.com/adver/selectadver/id/'.$id;
            $json.= "\n".'{'.'"width": "'.$context['width'].'",'."\n";
            $json.= "\n".'"height": "'.$context['height'].'",';                        
            $json.= "\n".'"href": "'.$href.'"'."\n";                        
            $json.= '},';                                                                                           
        }
        $json = substr($json, 0,-1);
        $this->_response->appendBody($json);
        echo '], ', "\n", "\n" ,'"status": "OK"', "\n", '}';
    }
    
    public function generateadvcontextAction() {
                
        $id = Zend_Auth::getInstance()->getIdentity()->id;
        
        //генерируем уникальный код
        $code =  sha1(uniqid(rand(mktime(), true),true));
        
        $data = array(
            'id_publisher' => $id,
            'id_site' => $this->_getParam('site'),
            'id_type_adver' => $this->_getParam('type'),
            'code' => $code,
            'width' => $this->_getParam('width'),
            'height' => $this->_getParam('height')
        );
        
        $obj = new Application_Model_Adver();
        $status = $obj->addAdverSpace($data);
        
        if(isset($status)) {
            $json = '{"res":[{"code": "'.$code.'"}]}';
            $this->_response->appendBody($json);
             
        }  
    }
    
    public function regionsAction() {
        $campaigns = new Adv_Model_Campaigns();
        $id = $this->_getParam('id');
        $allRegions = $campaigns->getAllRegionsCountry($id);
        $json = '{"regions":['."\n";
        foreach ($allRegions as $key => $region) {                        
            $json.= "\n".'{'.'"id": "'.$region['id'].'",'."\n";
            $json.= "\n".'"name": "'.$region['name'].'"';                                    
            $json.= '},';                                                                                   
        }
        $json = substr($json, 0,-1);
        $this->_response->appendBody($json);
        echo '], ', "\n", "\n" ,'"status": "OK"', "\n", '}';
    }
    /**
     * Сохраняем настройки сгенерированного контекстного банера 
     */
    public function savestylesettingsAction() {
        
        $validate = new Zend_Filter();
        $validate->addFilter(new Zend_Filter_StringTrim())
                 ->addFilter(new Zend_Filter_StripTags());
                        
        $data = array(
            'font_weight' => $validate->filter($this->_getParam('font_weight')),
            'font_style'  => $validate->filter($this->_getParam('font_style')),
            'text_decoration' => $validate->filter($this->_getParam('text_decoration')),
            'font_family' => $validate->filter($this->_getParam('font_family')),
            'font_size' => $validate->filter($this->_getParam('font_size')),
            'color' =>  '#'.$validate->filter($this->_getParam('color')),
            'bgcolor' => '#'.$validate->filter($this->_getParam('bgcolor')),
            'id_site' => $validate->filter($this->_getParam('site'))
        );
        //сохраняем настройки в базу
        $obj = new Application_Model_Adver();
        $obj->saveContextSettings($data);
        
    }
    /**
     * Генерируем код баннера 
     */
    public function generateadvbannerAction() {
        $id_pub = Zend_Auth::getInstance()->getIdentity()->id;
        $validate = new Zend_Filter();
        $validate->addFilter(new Zend_Filter_StringTrim())
                ->addFilter(new Zend_Filter_StripTags);
        
        //генерируем уникальный код
        $code =  sha1(uniqid(rand(mktime(), true),true));
        
        $data = array(
            'id_publisher' => $id_pub,
            'id_site' => $validate->filter($this->_getParam('site')),
            'id_type_adver' => 1,
            'id_category_banner' => $validate->filter($this->_getParam('size')),
            'length_queue' => $validate->filter($this->_getParam('queue')),
            'code' => $code
        );
        $obj = new Application_Model_Adver();
        //добавляем новое рекламное место и возвращаем его id
        $last_id = $obj->addAdverSpace($data);
        //добавляем тип баннера который выбрал пользоавтель в связывающую таблицу
        $gif = $validate->filter($this->_getParam('gif'));
        $jpg = $validate->filter($this->_getParam('jpg'));
        $png = $validate->filter($this->_getParam('png'));
        $swf = $validate->filter($this->_getParam('swf'));
        if ($gif == 'yes') {
            $data_type = array (
                'id_advertising_space' => $last_id,
                'id_banner_type' => 1
            ); 
            $obj->addBannerType($data_type);
        }
        if ($jpg == 'yes') {
            $data_type = array (
                'id_advertising_space' => $last_id,
                'id_banner_type' => 2
            ); 
            $obj->addBannerType($data_type);
        }
        if ($png == 'yes') {
            $data_type = array (
                'id_advertising_space' => $last_id,
                'id_banner_type' => 3
            ); 
            $obj->addBannerType($data_type);
        }
        if ($swf == 'yes') {
            $data_type = array (
                'id_advertising_space' => $last_id,
                'id_banner_type' => 4
            ); 
            $obj->addBannerType($data_type);
        }
        //формируем код рекламного места
        if(isset($last_id)) {
            $json = '{"res":[{"code": "'.$code.'"}]}';
            $this->_response->appendBody($json);
             
        } 
        
    }
 }
